﻿using System;

namespace Jaiden.IO
{
    public static class SizeHelper
    {
        private static readonly long[] FileLengthLimit =
        {
            0L,
            1024L, // 1024^1
            1048576L, // 1024^2
            1073741824L, // 1024^3
            1099511627776L, // 1024^4
            1125899906842624L // 1024^5
        };

        private static readonly string[] FileLengthUnit =
        {
            "Byte",
            "KB",
            "MB",
            "GB",
            "TB",
            "PB"
        };

        public static string GetSizeDisplay(long size)
        {
            if (size < 0) throw new ArgumentOutOfRangeException(nameof(size));
            var length = size;
            for (var i = 0; i < FileLengthLimit.Length; i++)
            {
                if (length >= FileLengthLimit[i]) continue;
                var val = FileLengthLimit[i - 1] == 0 ? length : length / Convert.ToDecimal(FileLengthLimit[i - 1]);
                val = Math.Floor(val * 100) / 100;
                if (length < 1024) return $"{val:0} {FileLengthUnit[i - 1]}";
                return $"{val:F2} {FileLengthUnit[i - 1]}";
            }

            return $"{size} bytes";
        }
    }
}